package com.calvin.study.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;

import org.springframework.core.io.support.PropertiesLoaderUtils;

public class ReflectDemo1 {
	
	public static void main(String[] args) {
		try {
			Properties prop = new Properties();
			prop = PropertiesLoaderUtils.loadAllProperties("reflect.properties");
			String className = prop.get("class").toString();
			System.out.println("获取配置文件class属性 ==> \t" + className);
			String methodName = prop.getProperty("method");
			System.out.println("获取配置文件method属性 ==> \t" + methodName);
			
			//Class类型的clazz对象
			Class cls = Class.forName(className);
			Object obj = cls.newInstance();
			System.out.println(obj.getClass());
			
			//获取该类的eat方法
			Method md = cls.getMethod(methodName);
			md.invoke(obj);//执行该方法
			
			//getField不能获取私有属性 java.lang.NoSuchFieldException: name
			//Field nameField = cls.getField("name");
			//System.out.println(nameField);
			
			//获得sex字段值
			Field nameField = cls.getField("sex");
			System.out.println(nameField.get(obj));
			
			//获取构造器，同时可以给构造器指定参数类型
			Constructor con = cls.getConstructor();
			System.out.println(con);
			
			Constructor con2 = cls.getConstructor(String.class);
			System.out.println(con2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
